<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../layui/css/layui.css">
</head>
<body>
    <!-- 导航地址 -->
      <div style="margin:20px 20px;">
        <span class="layui-breadcrumb">
            <a>学生管理</a>
            <a>学生信息列表</a>
          </span>      
      </div>
       <a style="margin-left: 20px;" class="layui-btn layui-btn-normal" href="./addStudent.html">
        添加学生<i class="layui-icon layui-icon-user"></i> 
        &nbsp; 
    </a>
      <hr>
      <table class="layui-table" border="1" style="margin-top:20px">
          <thead>
              <th>编号</th>
              <th>姓名</th>
              <th>性别</th>
              <th>年龄</th>
              <th>分数</th>
              <th>操作</th>
          </thead>
          <tbody id="showData"></tbody>
      </table>
</body>
</html>
<script src='../lib/jquery.min.js'></script>
<script src='../layui/layui.js'></script>
<script>
layui.use('element', function(){
  let element = layui.element; //导航的hover效果、二级菜单等功能，需要依赖element模块
});
</script>
<script>
    function getData(){
        $.ajax({
        type:"get",
        url:"/api/student/showInfos",
        dataType:"json",
        headers:{
            "Authorization":localStorage.getItem('_t')
        },
        success(result){
            console.log(result);
            if(result.code==1){
                 alert(result.msg);
                 window.top.location.href="../login.html";
            }
            let str="";
            for(let i=0;i<result.length;i++){
                str+=`<tr>
                         <td>${result[i]._id}</td>
                         <td>${result[i].name}</td>
                         <td>${result[i].gender}</td>
                         <td>${result[i].age}</td>
                         <td>${result[i].score}</td>
                         <td><button class='delBtn layui-btn layui-btn-danger' id="${result[i]._id}">删除</button></td>
                       </tr>`;
            }
            $("#showData").html(str);
        }
    })
    }
    getData();
    //使用事件委托来绑定事件
   $("#showData").on("click",".delBtn",()=>{
   
    if(e.target.nodeName==="BUTTON"){
        let result =  window.confirm("你确定删除吗？");
        if(result){

   //通过事件源获得该对象的id属性
   let studentId = e.target.id;
    //alert(studentId)
    $.ajax({
        type:"post",
        url:"http://localhost:3000/student/del",
        data:{
            "studentId":studentId
        },
        dataType:"json",
        success(result){
            if(result.code==0){
                  alert(result.msg);
                        //重新获得数据
                        getData();
            }else{
                alert(result.msg);
            }
        }
    });
 }
}
}    
   )

</script>